

/*
 * Copyright 2002-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package thomas.studio.spring.security.ldap.config;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.kerberos.authentication.KerberosAuthenticationProvider;
import org.springframework.security.kerberos.authentication.KerberosServiceAuthenticationProvider;
import org.springframework.security.kerberos.authentication.sun.SunJaasKerberosClient;
import org.springframework.security.kerberos.authentication.sun.SunJaasKerberosTicketValidator;
import org.springframework.security.kerberos.web.authentication.SpnegoAuthenticationProcessingFilter;
import org.springframework.security.kerberos.web.authentication.SpnegoEntryPoint;
import org.springframework.security.ldap.userdetails.LdapUserDetailsManager;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import thomas.studio.spring.security.ldap.securityprovider.LdapAuthenticationProvider;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private  LdapUserDetailsManager ldapUserDetailsManager;
	
	@Autowired
	private LdapAuthenticationProvider ldapAuthenticationProvider;
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http            .exceptionHandling()
        .authenticationEntryPoint(spnegoEntryPoint())
        .and()
        .authorizeRequests()
					.antMatchers("/css/**", "/index").permitAll()
					.antMatchers("/user/**").hasRole("USER")
					.and().formLogin().loginPage("/login").failureUrl("/login-error")
					.and().logout().logoutUrl("/logout").logoutSuccessUrl("/login")
		 .and()
         .addFilterBefore(
                 spnegoAuthenticationProcessingFilter(),
                 BasicAuthenticationFilter.class);
					
	}



    @Override
    protected void configure(AuthenticationManagerBuilder auth)
    		throws Exception {
        auth
            .authenticationProvider(kerberosAuthenticationProvider())
            .authenticationProvider(kerberosServiceAuthenticationProvider())
            .authenticationProvider(ldapAuthenticationProvider)
            ;
    }

    @Bean
    public KerberosAuthenticationProvider kerberosAuthenticationProvider() {
        KerberosAuthenticationProvider provider =
        		new KerberosAuthenticationProvider();
        SunJaasKerberosClient client = new SunJaasKerberosClient();
        client.setDebug(true);
        provider.setKerberosClient(client);
        provider.setUserDetailsService(userDetailsService());
        return provider;
    }
    
    public UserDetailsService userDetailsService() { 	
    	return ldapUserDetailsManager;
    }

    @Bean
    public SpnegoEntryPoint spnegoEntryPoint() {
        return new SpnegoEntryPoint("/login");
    }

    @Bean
    public SpnegoAuthenticationProcessingFilter spnegoAuthenticationProcessingFilter() throws Exception {
        SpnegoAuthenticationProcessingFilter filter =
        		new SpnegoAuthenticationProcessingFilter();
        filter.setAuthenticationManager(authenticationManager());
        return filter;
    }

    @Bean
    public KerberosServiceAuthenticationProvider kerberosServiceAuthenticationProvider() throws IOException {
        KerberosServiceAuthenticationProvider provider =
        		new KerberosServiceAuthenticationProvider();
        provider.setTicketValidator(sunJaasKerberosTicketValidator());
        provider.setUserDetailsService(userDetailsService());
        return provider;
    }

    @Bean
    public SunJaasKerberosTicketValidator sunJaasKerberosTicketValidator() throws IOException {
        SunJaasKerberosTicketValidator ticketValidator = new SunJaasKerberosTicketValidator();
        ticketValidator.setServicePrincipal("HTTP/www.tmstu.com@THOMAS.COM");
        PathMatchingResourcePatternResolver pathResolver = new PathMatchingResourcePatternResolver();
        Resource keytabResource = pathResolver.getResource("classpath:kerberos/http.keytab");
        ticketValidator.setKeyTabLocation(new FileSystemResource(keytabResource.getFile()));
        ticketValidator.setDebug(true);
        return ticketValidator;
    }
	
    /*
	@Override
	protected AuthenticationManager authenticationManager() throws Exception {
		ProviderManager authenticationManager = new ProviderManager(Arrays.asList(
				kerberosServiceAuthenticationProvider(),
				ldapAuthenticationProvider));

		authenticationManager.setEraseCredentialsAfterAuthentication(false);
		return authenticationManager;			
	}
	*/
}